<!--
@Create By Tim For 19/08/14
@单点登录成功回调组件
-->
<template>
  <div class="CodeCallbackContainer"></div>
</template>
<script>
import {config, tool, getDefaultIndex, getIndexPage, getSysMenuDefault} from 'elead-ui-tool-v3'
import ssoApi from '@/api/auth/sso2Api'
import permissionApi from '@/api/sys/permissionApi'
//import PersonalDirectoryApi from '@/api/file/personalDirectoryApi'
import dictApi from '@/api/dev/dictApi'
import configApi from '@/api/dev/configApi'
import {message} from 'ant-design-vue'
import {isFrame} from '@/utils/other'
import userCenterApi from '@/api/sys/userCenterApi'
import {libFlowPackageMethods} from "@/utils/exportInstallMethods";
export default {
  name: 'authLoginCodeCallback',
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect_uri
      },
      immediate: true
    }
  },
  data() {
    return {}
  },
  mounted() {
    const {redirect_uri, code} = this.getParams()
    this.handleCallback({redirectUri: redirect_uri, code})
  },
  methods: {
    getParams(name, defaultValue) {
      // 获取当前url
      const parameterObject = {}
      const url = window.location.href
      let parameter = url.split('?')[1]
      if (!parameter) {
        // 这个界面无参数属于非法访问，跳转到登录界面让他登录去
        // window.location.href = '/login'
        return parameterObject
      }
      const parameterArray = parameter.split('&')
      // 当然了，不可能只有一个参数
      if (!parameterArray) {
        // window.location.href = '/login'
        return parameterObject
      }
      // 遍历数组，拿到json对象
      for (let i = 0; i < parameterArray.length; i++) {
        parameterObject[parameterArray[i].split('=')[0]] = parameterArray[i].split('=')[1]
      }
      return parameterObject
    },
    async handleCallback({redirectUri, code}) {
      let token = ''
      /*iframe 嵌套逻辑*/
      if (isFrame()) {
        let f = async () => {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              resolve(tool.data.get('TOKEN'))
            }, 100)
          })
        }
        token = await f()
      } else {
        token = await ssoApi.codeCallback(redirectUri, code)
      }
      // 成功换取到token,将token保存到cookie
      tool.data.set('TOKEN', token)
      //获取用户信息
      const loginUser = await ssoApi.getInfo()
      let roleCodes = await permissionApi.roleCodeInfo({userId: loginUser.id})
      //文件系统特殊逻辑
      try {
        if (libFlowPackageMethods.PersonalDirectoryApi) {
          if (!roleCodes || roleCodes.indexOf('default') === -1) {
            await libFlowPackageMethods.PersonalDirectoryApi.grantDefaultRole()
            roleCodes = await permissionApi.roleCodeInfo({userId: loginUser.id})
          }
        }
      } catch (e) {
      }
      // 获取 buttonCodeList
      const permissions = await permissionApi.permissionInfo({userId: loginUser.id})
      loginUser.buttonCodeList = permissions
      loginUser.roleCodeList = roleCodes
      tool.data.set('USER_INFO', loginUser)
      // 获取用户的菜单
      const menu = await getSysMenuDefault({userCenterApi}).catch((err) => {
        this.islogin = false
        return
      })
      getDefaultIndex(menu, null)
      tool.data.set('MENU', menu)
      getIndexPage({
        menu, success: (_defaultIndex) => {
          this.$router.replace({
            path: _defaultIndex.cur.path
          })
        }
      })
      message.success('登录成功')
      nextTick(() => {
        // 配置
        if (!tool.data.get('SNOWY_SYS_BASE_CONFIG')) {
          let formData = ref(config.SYS_BASE_CONFIG)
          configApi.configSysBaseList().then((data) => {
            if (data) {
              data.forEach((item) => {
                formData.value[item.configKey] = item.configValue
              })
              tool.data.set('SNOWY_SYS_BASE_CONFIG', formData.value)
              this.$store.commit('SET_sysBaseConfig', formData.value)
            }
          })
        }
        // 字典
        dictApi.dictTree().then((data) => {
          // 设置字典到store中
          tool.data.set('DICT_TYPE_TREE_DATA', data)
        })
        /*iframe 嵌套逻辑*/
        if (isFrame()) {
          window.parent.postMessage('potalIframeReady', '*')
        }
      })
    }
  }
}
</script>
